package com.xxh.blog.shiro;

import com.xxh.blog.dao.UserDao;
import com.xxh.blog.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

@Component
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    UserDao userDao;

    @Resource
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        AccountProfile profile=(AccountProfile) principal.getPrimaryPrincipal();
        if(profile.getUsername().equals("admin")){
            Set<String> roles = new HashSet<>();
            roles.add("admin");
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
            return info;
        }
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;

        AccountProfile profile=userService.login(token.getUsername(),String.valueOf(token.getPassword()));

        SecurityUtils.getSubject().getSession().setAttribute("profile",profile);

        System.out.println(token.getPrincipal());

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(profile, token.getCredentials(), getName());
        return info;
    }
}
